import { Byte } from '../../api/io/Byte';
import { Role } from './Role';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';
import { MathUtils } from '../../api/math/MathUtils';



/**角色列表属性枚举*/
export const enum E_RoleList {
	/**用户id*/
	USER_ID = 0,
	/**角色*/
	ROLE = 1,
	/**枚举数量*/
	EnumCount = 2
}


/**角色列表*/
export class RoleList {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_ROLE_LIST_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_ROLE_LIST_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: RoleList[] = [];

	/**创建入口*/
	public static create(json?: string): RoleList {
		const c = this.POOL.pop() || new RoleList();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/**用户id (uint32)*/
	protected _userId: number;
	/**角色*/
	protected _role: Role[] = [];


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (RoleList.POOL.indexOf(this) === -1) {
			RoleList.POOL.push(this);
		}
	}

	/**用户id*/
	public get userId() {
		return this._userId;
	}


	/**用户id*/
	public set userId(v: number) {
		this._userId = v;
	}


	/**增加角色*/
	public addRole(v: Role): void {
		if (this._role.indexOf(v) === -1) {
			this._role.push(v);
		}
	}

	/**删除角色*/
	public removeRole(v: Role): void {
		const idx = this._role.indexOf(v);
		if (idx >= 0) {
			this._role.splice(idx, 1);
		}
	}

	/**获取角色列表*/
	public getRoleList(): Role[] {
		return this._role;
	}


	/**通过枚举获取值*/
	public getV(k: E_RoleList): any {
		switch (k) {
			case E_RoleList.USER_ID: return this._userId;
			case E_RoleList.ROLE: return this._role;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_RoleList, v: any): void {
		switch (k) {
			case E_RoleList.USER_ID: this._userId = v; break;
			case E_RoleList.ROLE: this._role = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		//用户id
		this._userId = 0;
		//角色
		if (this._role) {
			const list = this._role;
			for (let i = 0, len = list.length; i < len; i++) {
				list[i].destroy();
			}
			this._role.length = 0;
		}
		else {
			this._role = [];
		}
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._userId) {
			json.userId = this._userId;
		}
		if (this._role) {
			const list: string[] = [];
			const vs = this._role;
			for (let i = 0, len = vs.length; i < len; i++) {
				list[i] = vs[i].stringify(false);
			}
			json.role = list;
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.userId) {
			this._userId = json.userId;
		}
		if (json.role) {
			const list = json.role;
			for (let i = 0, len = list.length; i < len; i++) {
				this._role.push(Role.create(list[i]));
			}
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		byte.writeUint32(this._userId);
		//角色
		{
			const list = this._role;
			if (list) {
				byte.writeUint32(list.length);
				for (let i = 0, len = list.length; i < len; i++) {
					list[i].toBytes(byte);
				}
			}
			else {
				byte.writeUint32(0);
			}
		}
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		this._userId = byte.readUint32();
		//角色
		{
			const len = byte.readUint32();
			for (let i = 0; i < len; i++) {
				const cv = Role.create();
				cv.fromBytes(byte);
				this._role[i] = cv;
			}
		}
		return this;
	}


	/**克隆*/
	public clone(): RoleList {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = RoleList.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = RoleList.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];
			//用户id
			if (idx === E_RoleList.USER_ID) {
				const oldv = this._userId;
				this._userId = us[i + 1];
				IAsync.dispatch(eventID, idx, this._userId, oldv);
				i += 2;
				continue;
			}
			//角色
			if (idx === E_RoleList.ROLE) {
				const c: number = us[i + 1];
				const v = Role.create(us[i + 2]);
				IAsync.dispatch(eventID, idx, c, v);
				i += 3;
				continue;
			}

			console.error('[Struct Data] can not find enum in RoleList with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: RoleList): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];

		if (this._userId !== other._userId) {
			updates.push(E_RoleList.USER_ID, this._userId);
		}

		//角色
		{
			const idx = E_RoleList.ROLE;
			const rs = MathUtils.intersectSortedArray(this._role, other._role);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const newv = list[i];
					updates.push(idx, 1, newv.stringify(false));
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const newv = list[i];
					updates.push(idx, 1, newv.stringify(false));
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					const oldv = list[i];
					updates.push(idx, 0, oldv.getV(0));
				}
			}
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(RoleList.TOTAL_EVENT_ID, this.getV(0));
	}

}
